/*
 * @Author: your name
 * @Date: 2021-04-28 08:52:59
 * @LastEditTime: 2021-04-28 16:09:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \js_study\demo05\js\index.js
 */


((doc)=>{

    var Tab = function (options){
        const oTab = doc.querySelector(options.el);
        this.oNavs = oTab.getElementsByClassName("nav")[0];
        this.oNavItems = oTab.getElementsByClassName("nav_item");
        this.oPages = oTab.getElementsByClassName("page_item");

        this.cuerrentIndex = 0;
    };

    // 初始化方法
    Tab.prototype.init = function (){
        this.bindEvent();
    };

    // 绑定事件处理函数
    Tab.prototype.bindEvent = function (){
        this.oNavs.addEventListener('click',this.onNavClick.bind(this),false);
    };

    // 点击事件
    Tab.prototype.onNavClick = function (ev){
        const e = ev || window.event,
              tar = e.target || e.srcElement,
              tarClassName = tar.className;

        if(tarClassName === "nav_item"){
            this.changeTabItem(tar);
        }
    };

    // 切换tab对应页面
    Tab.prototype.changeTabItem = function(target){
        // this.oNavItems[this.cuerrentIndex].className = "nav_item";
        // this.oPages[this.cuerrentIndex].className = "page_item";
        this.cssUpdate(this.oNavItems,"remove","nav_item");
        this.cssUpdate(this.oPages,"remove","page_item");
        this.cuerrentIndex = [].indexOf.call(this.oNavItems,target);
        // this.oNavItems[this.cuerrentIndex].className += " current";
        // this.oPages[this.cuerrentIndex].className += " current";
        this.cssUpdate(this.oNavItems,"add");
        this.cssUpdate(this.oPages,"add");
    };

    // class样式操控
    Tab.prototype.cssUpdate = function(selectDom,method, cssStyle){
        switch(method){
            case "add":
                selectDom[this.cuerrentIndex].className += " current";
                break;
            case "remove":
                selectDom[this.cuerrentIndex].className = cssStyle;
                break;
            default:
                break;
        }
    };
    
    window.Tab = Tab;  //让项目可以全局访问调用这个Tab方法
})(document);